<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License. 
-->
<html>
<head>
    <link type="text/css" rel="stylesheet" href="https://struts.apache.org/css/default.css">
    <style type="text/css">
        .dp-highlighter {
            width:95% !important;
        }
    </style>
    <style type="text/css">
        .footer {
            background-image:      url('https://cwiki.apache.org/confluence/images/border/border_bottom.gif');
            background-repeat:     repeat-x;
            background-position:   left top;
            padding-top:           4px;
            color:                 #666;
        }
    </style>
    <link href='https://struts.apache.org/highlighter/style/shCoreStruts.css' rel='stylesheet' type='text/css' />
    <link href='https://struts.apache.org/highlighter/style/shThemeStruts.css' rel='stylesheet' type='text/css' />
    <script src='https://struts.apache.org/highlighter/js/shCore.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushPlain.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushXml.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJava.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJScript.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushGroovy.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushBash.js' type='text/javascript'></script>
    <script type="text/javascript">
        SyntaxHighlighter.defaults['toolbar'] = false;
        SyntaxHighlighter.all();
    </script>
    <script type="text/javascript" language="javascript">
        var hide = null;
        var show = null;
        var children = null;

        function init() {
            /* Search form initialization */
            var form = document.forms['search'];
            if (form != null) {
                form.elements['domains'].value = location.hostname;
                form.elements['sitesearch'].value = location.hostname;
            }

            /* Children initialization */
            hide = document.getElementById('hide');
            show = document.getElementById('show');
            children = document.all != null ?
                    document.all['children'] :
                    document.getElementById('children');
            if (children != null) {
                children.style.display = 'none';
                show.style.display = 'inline';
                hide.style.display = 'none';
            }
        }

        function showChildren() {
            children.style.display = 'block';
            show.style.display = 'none';
            hide.style.display = 'inline';
        }

        function hideChildren() {
            children.style.display = 'none';
            show.style.display = 'inline';
            hide.style.display = 'none';
        }
    </script>
    <title>Unit Testing</title>
</head>
<body onload="init()">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
    <tr class="topBar">
        <td align="left" valign="middle" class="topBarDiv" align="left" nowrap>
            &nbsp;<a href="home.html">Home</a>&nbsp;&gt;&nbsp;<a href="tutorials.html">Tutorials</a>&nbsp;&gt;&nbsp;<a href="getting-started.html">Getting Started</a>&nbsp;&gt;&nbsp;<a href="unit-testing.html">Unit Testing</a>
        </td>
        <td align="right" valign="middle" nowrap>
            <form name="search" action="https://www.google.com/search" method="get">
                <input type="hidden" name="ie" value="UTF-8" />
                <input type="hidden" name="oe" value="UTF-8" />
                <input type="hidden" name="domains" value="" />
                <input type="hidden" name="sitesearch" value="" />
                <input type="text" name="q" maxlength="255" value="" />
                <input type="submit" name="btnG" value="Google Search" />
            </form>
        </td>
    </tr>
</table>

<div id="PageContent">
    <div class="pageheader" style="padding: 6px 0px 0px 0px;">
        <!-- We'll enable this once we figure out how to access (and save) the logo resource -->
        <!--img src="/wiki/images/confluence_logo.gif" style="float: left; margin: 4px 4px 4px 10px;" border="0"-->
        <div style="margin: 0px 10px 0px 10px" class="smalltext">Apache Struts 2 Documentation</div>
        <div style="margin: 0px 10px 8px 10px"  class="pagetitle">Unit Testing</div>

        <div class="greynavbar" align="right" style="padding: 2px 10px; margin: 0px;">
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=27838592">
                <img src="https://cwiki.apache.org/confluence/images/icons/notep_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Edit Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=27838592">Edit Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">
                <img src="https://cwiki.apache.org/confluence/images/icons/browse_space.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Browse Space"></a>
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">Browse Space</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=27838592">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_page_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=27838592">Add Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=27838592">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_blogentry_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add News"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=27838592">Add News</a>
        </div>
    </div>

    <div class="pagecontent">
        <div class="wiki-content">
            <div id="ConfluenceContent"><div class="confluence-information-macro confluence-information-macro-information"><span class="aui-icon aui-icon-small aui-iconfont-info confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The example code for this tutorial, unit_testing, is available at <a shape="rect" class="external-link" href="https://github.com/apache/struts-examples" rel="nofollow">https://github.com/apache/struts-examples</a></p></div></div><h3 id="UnitTesting-Introduction">Introduction</h3><p>Struts 2 supports running unit tests of methods in the Struts Action class with the <a shape="rect" class="external-link" href="http://struts.apache.org/2.3.1.2/docs/junit-plugin.html">Struts 2 JUnit plugin</a>. The JUnit plugin allows you to test methods of an Action class from within the Struts 2 framework. The Struts Servlet filter and interceptors fire just as if your application was running on a Servlet container.</p><div class="confluence-information-macro confluence-information-macro-tip"><span class="aui-icon aui-icon-small aui-iconfont-approve confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The <a shape="rect" class="external-link" href="http://struts.apache.org/mail.html">Struts 2 user mailing list</a> is an excellent place to get help. If you are having a problem getting the tutorial example applications to work search the Struts 2 mailing list. If you don't find an answer to your problem, post a question on the mailing list.</p></div></div><h3 id="UnitTesting-Setup">Setup</h3><p>The Struts 2 JUnit plugin jar file must be on your application's class path. In the example application (see info above) the pom.xml includes a dependency for the struts2-junit-plugin. There are numerous transitive dependencies, including to JUnit and the Spring framework.</p><h3 id="UnitTesting-WritingAUnitTest">Writing A Unit Test</h3><p>In the example application, the Register Action class includes using the validate method. This method is automatically executed by the Struts 2 framework prior to the execute method. Additionally, this method needs the values from the user's input on the form to already have been provided to the instance fields of the Action class (this work is done by another Struts 2 interceptor). So it would be difficult to test the validate method without the overall Struts 2 framework running.</p><p>To use the Struts 2 plugin to ensure the Strut 2 framework runs as part of the test, you need to have your JUnit test class extend StrutsTestCase (see RegisterTest class in the example application).</p><div class="confluence-information-macro confluence-information-macro-information"><span class="aui-icon aui-icon-small aui-iconfont-info confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>Note that the Struts 2 JUnit plugin can be used to design unit tests of other Action class methods such as the input method and also to test methods of a custom interceptor you add to the interceptor stack. Also in this example, the test is for validation performed in the <a shape="rect" href="form-validation.html">validate method</a>. But the same type of test would work if the validation was done using <a shape="rect" href="form-validation-using-xml.html">XML file validation</a>.</p></div></div><p>To test the validate method we want Struts to call the Struts action that will cause the Action class's validate and execute methods to be run. In the example application this action is register.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>struts.xml</b></div><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">	  &lt;action name="register" class="org.apache.struts.register.action.Register" method="execute"&gt;
		&lt;result name="success"&gt;/thankyou.jsp&lt;/result&gt;
		&lt;result name="input"&gt;/register.jsp&lt;/result&gt;
	  &lt;/action&gt;

</pre>
</div></div><p>Remember the validate method will be called automatically by the framework before calling the execute method. If validation fails the Struts framework will return "input". If there are no validation errors then the framework will call the execute method and return whatever String the execute method returns.</p><h3 id="UnitTesting-TestValidationShouldPass">Test Validation Should Pass</h3><p>For our first test we'll test that there should be no validation errors. In the normal flow of this application the user would first enter the form data shown on the register.jsp page.</p><p><span class="confluence-embedded-file-wrapper"><img class="confluence-embedded-image confluence-content-image-border" src="unit-testing.data/Screen%20shot%202012-02-17%20at%202.46.54%20PM.png"></span></p><p>The input fields for the form have the following name values: personBean.firstName, personBean.lastName, personBean.email, and personBean.age. When the user fills out those fields Struts will take the values and provide them to the appropriate set methods of the personBean object. So as part of the test I need to simulate the user filling out these form fields. The StrutsTestCase provides a request object (of type MockHttpServletRequest) that I can use to set these values in the request scope.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>testExecuteValidationPasses method from RegisterTest class</b></div><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@Test
public void testExecuteValidationPasses() throws Exception() {

  request.setParameter("personBean.firstName", "Bruce");

  request.setParameter("personBean.lastName", "Phillips");
		
  request.setParameter("personBean.email", "bphillips@ku.edu");
		
  request.setParameter("personBean.age", "19");

  ActionProxy actionProxy = getActionProxy("/register.action");

  Register action = (Register) actionProxy.getAction() ;

  assertNotNull("The action is null but should not be.", action);

  String result - actionProxy.execute();

  assertEquals("The execute method did not return " + ActionSupport.SUCCESS + " but should have.", ActionSupport.SUCCESS, result);
  
}

</pre>
</div></div><p>The first statements in the test method use the request object to set the values of any request parameters. These simulate the values the user would enter into the form fields. Note how the first argument to setParameter is the same as the value of the name attribute in the Struts textfield tag in the register.jsp page.</p><p>In this test I'm providing good data for each form field as I want to ensure my validation doesn't register an error if the user provides correct information.</p><p>I then call the getActionProxy method with the argument of "/register.action" and then the getAction method to get a reference to the Struts action class for this test. This will ensure that the Struts 2 JUnit plugin will know which Action class should be used--the class associated with the register action in the struts.xml. In this case that class is the Register class.</p><p>The assertNotNull test ensures that argument to getActionProxy reference an Action class identified in struts.xml. It's a way of checking that you've correctly setup struts.xml for this action.</p><p>After that I can call actionProxy.execute(). This causes the Struts 2 framework to go through its normal process of Servlet fileter and interceptors for the action identified by the actionProxy (in this case that is the register.action). The validate method of class Register will get called and if it doesn't create any field or action errors then Struts 2 will call the execute method. In this example, the execute method should return "success".</p><p>So in the next statement, I check that success was returned.</p><h3 id="UnitTesting-TestValidationShouldFail">Test Validation Should Fail</h3><p>To test that validation should fail, I just need to have a test method that doesn't provide input for a form field. For example, in the validate method of the Register Action class, is a test to ensure the user has entered some information for the personBean.firstName input field. In the test method I would just not use the request object to set a parameter for that field.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>testExecuteValidationFailsMissingFirstName method from RegisterTest class</b></div><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@Test
public void testExecuteValidationFailsMissingFirstName() throws Exception() {

  //request.setParameter("personBean.firstName", "Bruce");

  request.setParameter("personBean.lastName", "Phillips");
		
  request.setParameter("personBean.email", "bphillips@ku.edu");
		
  request.setParameter("personBean.age", "19");

  ActionProxy actionProxy = getActionProxy("/register.action");

  Register action = (Register) actionProxy.getAction() ;

  assertNotNull("The action is null but should not be.", action);

  String result - actionProxy.execute();

  assertEquals("The execute method did not return " + ActionSupport.INPUT + " but should have.", ActionSupport.INPUT, result);
  
}

</pre>
</div></div><p>In the last assertEquals statement my test checks that the Struts 2 framework returned "input" as that is what the Struts 2 framework will return if the validation adds a field or action error.</p><h3 id="UnitTesting-Summary">Summary</h3><p>There is much more you can do with the Struts 2 JUnit plugin to help you test the methods of your Action class in conjunction with the Struts 2 fraemwork. If your Struts 2 application uses Spring to inject dependencies into the Action class then the Struts 2 JUnit Plugin has a StrutsSpringTestCase that your test class should extend. Please read <a shape="rect" class="external-link" href="http://struts.apache.org/2.3.1.2/docs/testing-actions.html">Testing Actions</a> to learn more.</p></div>
        </div>

        
    </div>
</div>
<div class="footer">
    Generated by CXF SiteExporter
</div>
</body>
</html>
